package com.qst.financing.controller;

import com.qst.financing.common.Result;
import com.qst.financing.common.StatusCode;
import com.qst.financing.dao.BankUserDao;
import com.qst.financing.entity.BankUser;
import com.qst.financing.entity.PasswordParam;
import com.qst.financing.security.service.JwtUserDetailsServiceImpl;
import com.qst.financing.security.util.JwtTokenUtil;
import com.qst.financing.service.BankUserService;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author qst
 * @Description 银行用户模块
 */
@RestController
@RequestMapping("/user")
public class BankUserController {
    @Autowired
    private BankUserService bankUserService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private JwtUserDetailsServiceImpl jwtUserDetailsService;
    @Autowired
    private BankUserDao bankUserDao;

    //用户登录之后，修改用户密码
    @Operation(summary = "用户登录之后，修改用户密码")
    @PostMapping("/loginUpdatePassword")
    public Result<String> loginUpdatePassword(@Validated @RequestBody PasswordParam passwordParam, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            StringBuffer stringBuffer = new StringBuffer();
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError objectError : allErrors) {
                stringBuffer.append(objectError.getDefaultMessage()).append("; ");
            }
            String s = stringBuffer.toString();
            System.out.println(s);
            return new Result<String>(false, StatusCode.ERROR, "密码修改失败", s);
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails principal = (UserDetails) authentication.getPrincipal();
        String username = principal.getUsername();
        BankUser bankUser = bankUserService.selectByUserName(username);
        //数据库密码
        String oldDataBasePassword = bankUser.getPassword();
        //传过来的老密码
        String oldPassword = passwordParam.getOldPassword();
//        String encode = passwordEncoder.encode(oldPassword);

        if (!passwordEncoder.matches(oldPassword, oldDataBasePassword)) {
            return new Result<String>(false, StatusCode.ERROR, "原密码输入错误", "原密码输入错误");
        }
        bankUser.setUserName(username);
        bankUser.setPassword(passwordParam.getNewPassword());
        bankUserService.update(bankUser);
        return new Result<String>(true, StatusCode.OK, "修改成功");
    }

    //用户登录之后，根据用户名展示个人信息
    @Operation(summary = "用户登录之后，根据用户名展示个人信息")
    @GetMapping("/loginSelectByUsername")
    public Result<BankUser> loginSelectByUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails principal = (UserDetails) authentication.getPrincipal();
        String username = principal.getUsername();
        BankUser bankUser = bankUserService.selectByUserName(username);
        return new Result<BankUser>(true, StatusCode.OK, "查询成功", bankUser);
    }

    //用户登录之后，根据用户名修改个人基本信息
    @Operation(summary = "用户登录之后，根据用户名修改个人基本信息")
    @PostMapping("/loginUpdateByUsername")
    public Result<String> loginUpdateByUsername(@Validated @RequestBody BankUser bankUser, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            StringBuffer stringBuffer = new StringBuffer();
            for (ObjectError error : allErrors) {
                System.out.println(error);
                stringBuffer.append(error.getDefaultMessage()).append("; ");
            }
            System.out.println(stringBuffer);
            String errorInfo = stringBuffer.toString();
            return new Result<String>(false, StatusCode.ERROR, "修改失败", errorInfo);
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails principal = (UserDetails) authentication.getPrincipal();
        String username = principal.getUsername();
        bankUser.setUserName(username);
        bankUserService.update(bankUser);
        UserDetails userDetails = jwtUserDetailsService.loadUserByUsername(username);
        String token = jwtTokenUtil.generateToken(userDetails);
        return new Result<String>(true, StatusCode.OK, "修改成功", token);
    }

    //根据用户名查询用户
    @Operation(summary = "根据用户名查询用户")
    @GetMapping("/search/{userName}")
    public Result selectByUserName(@PathVariable("userName") String userName) {
        BankUser bankUser = bankUserService.selectByUserName(userName);
        return new Result(true, StatusCode.OK, "查询成功", bankUser);
    }
}
